package pers.vic.blog.module.front.controller;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import pers.vic.blog.module.api.model.BlogThirdUser;
import pers.vic.blog.constant.ThirdProperties;
import pers.vic.blog.module.front.service.impl.GiteeAuthService;
import pers.vic.blog.module.front.service.impl.GithubAuthService;
import pers.vic.boot.base.exception.CommonException;

/**
 * @author Vic.xu
 * @description: 第三方登录
 * @date: 2020/7/21 0021 17:41
 */
@Controller
@RequestMapping("/third")
public class ThirdLoginController extends BaseFrontController {

    @Autowired
    private GiteeAuthService giteeuthService;

    @Autowired
    private GithubAuthService githubAuthService;

    @Autowired
    private ThirdProperties thirdProperties;

    /**
     * 前往第三方授权页面
     * @param type
     * @return
     */
    @GetMapping(value = "/grant/{type}")
    public String toGrant(@PathVariable String type){
        ThirdProperties.ThirdAuthConfig config = thirdProperties.getConfigByType(type);
        if(config == null ){
            throw new CommonException("不存在的授权方式");
        }
        if(StringUtils.isBlank(config.getRenderUrl())){
            throw new CommonException("没有配置授权url");
        }
        return "redirect:" + config.getRenderUrl();
    }

    /**
     * gitee callback
     * @param code
     * @return
     */
    @RequestMapping("/gitee")
    public Object gitee(String code){
        BlogThirdUser user = giteeuthService.findUserInfoByCode(code);
        setSessionAttribute(PRINCIPAL_SESSION, user);
        return "redirect:" + lastUrl();
    }

    @RequestMapping("/github")
    public Object github(String code){
        BlogThirdUser user = githubAuthService.findUserInfoByCode(code);
        setSessionAttribute(PRINCIPAL_SESSION, user);
        return "redirect:" + lastUrl();
    }

    @GetMapping("/logout")
    public String logout(){
        setSessionAttribute(PRINCIPAL_SESSION, null);
        return "redirect:/";
    }

}
